package com.srwl.mytx.widget.chatRow;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.core.content.ContextCompat;

import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.srwl.mytx.Constant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.IDUtils;
import com.srwl.mytx.utils.IMThumbnailUtils;
import com.srwl.mytx.utils.ImageUtils;

import java.io.File;

import butterknife.ButterKnife;


public class ChatRowImage extends ChatRowFile {

    private static final String TAG = "ChatRowImage";
    private ImageView imageView;


    public ChatRowImage(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }


    @Override
    protected void onFindViewById(View itemView) {
        percentageView = itemView.findViewById(R.id.percentage);
        imageView = itemView.findViewById(R.id.iv_picture);
    }


    @Override
    protected void onSetUpView() {
        if (isSendMessage) {
            imageView.setImageResource(R.drawable.ease_default_image);
            //即使是发送的消息，contend里面也可能是key而非完整的本地路径，所以需要判断
            // 转发的消息就是这样的情形，所以需要判断 content 是否是以文件存储路径开头，也就是判断是否是一条转发的消息，
            // 如果是转发消息需要组合成完整的路径。

            handleSendMessage();
            String previewUrl = message.getPreviewUrl();

            if (TextUtils.isEmpty(previewUrl)) {
                genSendMessagePreviewImage();
                previewUrl = message.getPreviewUrl();
            } else {
                //检查预览图文件是否存在,如果不存在，需要重新生成
                File file = new File(previewUrl);
                if (!file.exists()) {
                    Log.d(TAG, "本地预览图不存在，生成预览图，，，，:" + message.getId());
                    genSendMessagePreviewImage();
                    previewUrl = message.getPreviewUrl();
                }
            }

            showImage(previewUrl);

        } else {
            String imageKey = message.getContent();
            Integer downloadState = message.getDownloadState();
            //如果下载状态为空，说明是第一次加载，设置下载状态为初始化
            if (downloadState == null) {
                downloadState = Constant.MESSAGE_DOWNLOAD_STATE_INIT;
            }
            switch (downloadState) {
                case Constant.MESSAGE_DOWNLOAD_STATE_INIT:
                    Log.d(TAG, "初次加载图片文件:" + message.getId());
                    imageView.setImageResource(R.drawable.ease_default_image);
                    progressBar.setVisibility(View.VISIBLE);
                    percentageView.setVisibility(View.VISIBLE);
                    //又文件读写权限，才去下载文件，否则下载了保存也会报权限异常
                    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                        message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_LOADING);
                        downLoadImageFile(imageKey);
                    }
                    break;
                case Constant.MESSAGE_DOWNLOAD_STATE_LOADING:
                    progressBar.setVisibility(View.VISIBLE);
                    percentageView.setVisibility(View.VISIBLE);
                    imageView.setImageResource(R.drawable.ease_default_image);
                    break;
                case Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS:
                    showPreviewImage(imageKey);
                    break;
                case Constant.MESSAGE_DOWNLOAD_STATE_FAIL:
                    progressBar.setVisibility(View.INVISIBLE);
                    percentageView.setVisibility(View.INVISIBLE);
                    imageView.setImageResource(R.drawable.ease_default_image);
                    Integer reDownLoadCount = message.getReDownLoadCount();
                    if (reDownLoadCount == null) {
                        reDownLoadCount = 0;
                    }
                    if (reDownLoadCount < 2) {
                        message.setReDownLoadCount(reDownLoadCount + 1);
                        Log.d(TAG, "加载图片失败后重新加载:" + message.getId() + "当前重试次数：" + (reDownLoadCount + 1));
                        progressBar.setVisibility(View.VISIBLE);
                        message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_LOADING);
                        downLoadImageFile(imageKey);
                    }
            }

        }

    }

    /**
     * 发送消息生成预览图
     */
    private void genSendMessagePreviewImage() {
        String localFilePath = message.getLocalFilePath();
        if (TextUtils.isEmpty(localFilePath)) {
            localFilePath = Helper.getInstance().getFilePath() + File.separator + message.getContent();
        }
        genPreviewImage(localFilePath, IDUtils.genImageName());
        messageDao.update(message);
    }

    private void showPreviewImage(String imageKey) {
        progressBar.setVisibility(View.INVISIBLE);
        percentageView.setVisibility(View.INVISIBLE);
        //再次检查本地文件是否存在
        File file = new File(Helper.getInstance().getFilePath(), imageKey);
        //检查文件是否存在，如果不存在，需要重新下载
        if (!file.exists()) {
            Log.d(TAG, "图片文件不存在，再次加载文件:" + message.getId());
            downLoadImageFile(imageKey);
            return;
        }

        String previewUrl = message.getPreviewUrl();

        if (TextUtils.isEmpty(previewUrl)) {
            Log.d(TAG, "onSetUpView: 预览图片不存在，重新生成message" + message.toString());

            genPreviewImage(Helper.getInstance().getFilePath() + File.separator + imageKey, imageKey);
            messageDao.update(message);
//            Glide.with(activity).asBitmap().load(previewUrl).diskCacheStrategy(DiskCacheStrategy.ALL).into(new SimpleTarget<Bitmap>() {
//                @Override
//                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                    imageView.setImageBitmap(resource);
//                }
//            });
            showImage(previewUrl);

        } else {
//            Glide.with(activity).asBitmap().load(previewUrl).diskCacheStrategy(DiskCacheStrategy.ALL).error(R.drawable.ease_default_image).into(new SimpleTarget<Bitmap>() {
//                @Override
//                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                    imageView.setImageBitmap(resource);
//                }
//            });
            showImage(previewUrl);
        }
        // showImageView(localPath, imageView, null);
        //标记消息为已读，发送已读回执 给发送方
        if (message.getReadState() == Constant.MESSAGE_READ_STATE_UNREAD && chatRowCallBack != null) {
            chatRowCallBack.onMessageRead(message);
        }
    }

    private void showImage(String previewUrl) {
        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        Integer height = message.getHeight();
        Integer width = message.getWidth();
        if (height != null && width != null) {
            layoutParams.height = height;
            layoutParams.width = width;

        } else {
            Log.i(TAG, "showImage: 图片尺寸为空" + message.toString());
        }

//        layoutParams.height = Utils.dpToPx(200, activity);
//        layoutParams.width = Utils.dpToPx(200, activity);
        //Glide.with(activity).load(previewUrl).diskCacheStrategy(DiskCacheStrategy.ALL).dontAnimate().into(imageView);
        GlideLoadUtils.glideLoad(activity, previewUrl, imageView);
    }


    /**
     * 根据原图生成预览图，并保存在本地
     *
     * @param imageKey
     */
    private void genPreviewImage(String localPath, String imageKey) {

        //根据原图生成预览图
        //如果出现内存溢出，可以用以下方法加载
        //com.srwl.mytx.utils.IMFileTools.decodeBitmapWithBestSampleSize
        Bitmap originalBitmap = ImageUtils.getBitmap(localPath);
        if (originalBitmap == null) {
            Log.e(TAG, "genPreviewImage: 找不到原图:" + localPath);
            return;
        }

//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeFile(localPath, options);


        String previewPath = Helper.getInstance().getFilePath() + File.separator + "preview_" + imageKey;
        float scale = IMThumbnailUtils.getScale(originalBitmap.getWidth(), originalBitmap.getHeight(), context);

        if (scale != 1) {

            float scaleHeight = originalBitmap.getHeight() * scale;
            float scaleWidth = originalBitmap.getWidth() * scale;
            Bitmap scaleBitmap = IMThumbnailUtils.scaleBitmap((int) scaleWidth, (int) scaleHeight, false, originalBitmap);
            message.setHeight((int) scaleHeight);
            message.setWidth((int) scaleWidth);
            if (scaleBitmap != null) {

                String imageType = ImageUtils.getImageType(localPath);
                if (TextUtils.isEmpty(imageType)) {
                    imageType = "JPEG";
                }
                if (imageType.equals("JPEG")) {
                    boolean save = ImageUtils.save(scaleBitmap, previewPath, Bitmap.CompressFormat.JPEG, 90);
                    if (!save) {
                        Log.e(TAG, "genPreviewImage: 保存缩略图失败  " + message.toString());
                        return;
                    }
                } else if (imageType.equals("PNG")) {
                    boolean save = ImageUtils.save(scaleBitmap, previewPath, Bitmap.CompressFormat.PNG, 90);
                    if (!save) {
                        Log.e(TAG, "genPreviewImage: 保存缩略图失败  " + message.toString());
                        return;
                    }
                }
            } else {
                Log.e(TAG, "genPreviewImage: 生成缩略图失败 scaleBitmap 为空 " + message.toString());
                return;
            }

        } else {
            previewPath = localPath;
            //即使原图并不大，不需要生成预览图的情况下，也需要设置 图片的高宽，因为在加载图片之前，需要先设置imageView 高宽，否则可能出现用Glide加载出的图片小于本来的尺寸
            message.setHeight(originalBitmap.getHeight());
            message.setWidth(originalBitmap.getWidth());
        }


        message.setPreviewUrl(previewPath);
    }


    /**
     * 直接下载原图，因为下载原图的速度已经比较快了，
     * 如果某天觉得图片类型消息加载时间过长，就可以 使用阿里云oss 的图片压缩策略，加载缩放后的图片，做预览图，再加载原图，作为大图展示，
     *
     * @param imageKey
     */
    private void downLoadImageFile(String imageKey) {
        AliOssService.getInstance().downloadImage(imageKey, new AliOssService.OssListener() {
            @Override
            public void onProgressChange(int progress) {
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        percentageView.setText(progress + "%");
                    }
                });
            }

            @Override
            public void onSuccess(String objectKey) {
                String localPath = Helper.getInstance().getFilePath() + File.separator + objectKey;
                genPreviewImage(localPath, imageKey);
                message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_SUCCESS);
                messageDao.update(message);
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //adapter.notifyItemChanged(getAdapterPosition());
                        showPreviewImage(objectKey);
//                        if (chatRowCallBack != null) {
//                            chatRowCallBack.onFileMessageDownLoadComplete(position);
//                        }
                    }
                });
            }

            @Override
            public void onFailure(String errorCode, String content) {
                message.setDownloadState(Constant.MESSAGE_DOWNLOAD_STATE_FAIL);
                messageDao.update(message);
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyItemChanged(getAdapterPosition());
                    }
                });
            }

        });
    }


    @Override
    protected void onBubbleClick() {
        if (itemClickListener != null) {
            Info imageViewInfo = PhotoView.getImageViewInfo(imageView);
            if (imageViewInfo == null) {
                return;
            }
            Log.i(TAG, "onBubbleClick: " + imageViewInfo.toString());
            Rect globalVisibleRect = new Rect();
            imageView.getGlobalVisibleRect(globalVisibleRect);
            Log.i(TAG, "onBubbleClick: 全局可见RECT:" + globalVisibleRect);
            try {
                itemClickListener.onImageOrVideoRowClick(getAdapterPosition(), imageViewInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }


    public Info getImageRectInfo() {
        return PhotoView.getBigImageViewInfo(imageView);
    }

    public View getImageView() {
        return imageView;
    }
}
